package icu.liuwisdom.controller;

import com.alibaba.fastjson.JSONObject;
import icu.liuwisdom.entity.District;
import icu.liuwisdom.mapper.DistrictMapper;
import icu.liuwisdom.service.IDistrictService;
import icu.liuwisdom.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

/**
 * 区域控制器
 *
 * @author 郑涵文
 * @date 2023/02/08
 */
@RestController
public class DistrictController {

    @Value("${gaode.key}")
    private String key;

    @Autowired
    private IDistrictService districtService;

    @Autowired
    private HttpUtil httpUtil;

    @RequestMapping("/getDistrict")
    public boolean getDistrict() throws IOException {
        String url=String.format("https://restapi.amap.com/v3/config/district?key=%s&subdistrict=3&extensions=base",key);
        String result = httpUtil.run(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String infocode = jsonObject.getString("infocode");
        if ("10000".equals(infocode)){
            List<District> districts = JSONObject.parseArray(jsonObject.getString("districts"), District.class);
            List<District> dbDistrictList=new ArrayList<>();
            District district = districts.get(0);
            createDistrict(district,dbDistrictList,"ef69cf46-b7a4-4d54-98ce-32d3019e315b");
            return districtService.saveBatch(dbDistrictList);
        }
        return false;
    }

    private void createDistrict(District district,List<District> districts,String pid) {
        List<District> districtsList = district.getDistricts();
        if (null == districtsList || districtsList.size() ==0 ){
            district.setId(UUID.randomUUID().toString());
            district.setParentId(pid);
            district.setDelFlag(0);
            districts.add(district);
        }else {
            String id = UUID.randomUUID().toString();
            district.setId(id);
            district.setParentId(pid);
            district.setDelFlag(0);
            districts.add(district);
            for (District d : districtsList) {
                createDistrict(d,districts,id);
            }
        }

    }
}
